package com.xjoyt.pay.commons;

import java.util.Arrays;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;

import com.xjoyt.pay.vo.SignType;

public final class SignUtils {

	public final static String JOIN_WORDS = "&";

	public static String getSignature(Map<String, String> params, String signKey, SignType signType) throws Exception {
		String data = getString(params, signKey);
		String hex = (signType == null || SignType.MD5.equals(signType)) ? md5(data) : sha1(data);
		return hex.toUpperCase();
	}

	public static String getString(Map<String, String> params, String signKey) {
		String[] strings = params.keySet().toArray(new String[params.size()]);
		Arrays.sort(strings);
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < strings.length; i++) {
			if (i != 0) {
				builder.append(JOIN_WORDS);
			}
			String key = strings[i];
			builder.append(key);
			builder.append("=");
			builder.append(params.get(key));
		}
		builder.append(JOIN_WORDS);
		builder.append("key=");
		builder.append(signKey);
		return builder.toString();
	}

	public static String md5(String data) throws Exception {
		return DigestUtils.md5Hex(data);
	}

	public static String sha1(String data) throws Exception {
		return DigestUtils.sha1Hex(data);
	}
}
